<?php

	/**
	 * Customers controller class
	 * @version 1.0
	 * @package controllers
	*/
	Class CustomersController extends Controller 
	{
		public $page_title = LANG_CUSTOMERS;
		public $layout = 'main';
		public $module = 'administration';
		public $name = 'customers';
		public $localName = LANG_CUSTOMERS;
		public $metaName = META_NAME_CUSTOMERS;
		public $metaDescription = META_DESCRIPTION_CUSTOMERS;
		public $helpers = array('html', 'htmlx', 'htmls', 'grids', 'toolbars');
		public $javascript = array();
		public $publicPages = array('login', 'logout', 'recover');
		public $privatePages = array('stats', 'profile', 'updateprofile', 'updateinterests', 'updatelocations', 'updatelanguages');
		public $components = array('pagination/pagination', 'webservice/webservice');
		
		
		/* PUBLIC PAGES */
		
		/**
		 * Login page
		 * TODO: Login functionality
		 *
		 */
		function Login()
		{			
			$this->layout = 'site';
			$this->hasLeftColumn = false;
			$this->page_title = Language::Get('Login');
			
			//authentication
			if (HTTPContext::IsPostBack())
			{
				//validation
				if (!filter_var(HTTPContext::$post['email'], FILTER_VALIDATE_EMAIL)) $this->controller_model->validation_errors['email'] = Language::Get('Should be valid email');
				if (empty(HTTPContext::$post['email'])) $this->controller_model->validation_errors['email'] = Language::Get('Email is required');
				if (empty(HTTPContext::$post['password'])) $this->controller_model->validation_errors['password'] = Language::Get('Password is required');

				if (empty($this->controller_model->validation_errors))
				{
					$this->data['message']['text'] = Language::Get('Login or password are incorrect');
					$this->data['message']['cssClass'] = 'error';
					
//					//authentication
//					$webService = new WebService();
//					$authResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
//						, "authenticateWorker"
//						, array('authenticateWorker' => array('email' => HTTPContext::$post['email'], 'password' => HTTPContext::$post['password']))
//						, array('XML_object_by_attributes' => true)
//						, array('SOAPAction' => 'authenticateWorker'));					
//					
//					if (empty($authResult))
//					{
//						$this->data['message']['text'] = Language::Get('Login or password are incorrect');
//						$this->data['message']['cssClass'] = 'error';
//					}
//					else if (!empty($authResult['faultcode']))
//					{
//						$this->data['message']['text'] = Language::Get('Server error has occured. Please, try again.');
//						$this->data['message']['cssClass'] = 'error';
//					}
//					else if (!empty($authResult['worker']))
//					{
//						//remember me
//						if (HTTPContext::$post['remember_me'])
//						{
//						    setcookie('email', HTTPContext::$post['password'], time()+(5*86400), '/');
//						    setcookie('password', HTTPContext::$post['password'], time()+(5*86400), '/');
//						}
//						else
//						{
//						    setcookie('email', '', time()+(5*86400), '/');
//						    setcookie('password', '', time()+(5*86400), '/');
//						}
//	
//						//registering into session
//						$_SESSION['customer'] = array();
//						foreach ($authResult['worker'] as $property => $value)
//						{
//							$property = str_replace('!', '', $property);
//							$_SESSION['customer'][$property] = $value;
//						}
//						
//						$this->Redirect('customers/stats/');
//					}
				}
				else 
				{
					
				}
			}
			else
			{
				$this->request->post['email'] = $_COOKIE['email'];
				$this->request->post['password'] = $_COOKIE['password'];
			}
		}
		
		/**
		 * Password recovery
		 *
		 */
		function Recover()
		{
			$this->page_title = Language::Get('Recover');
			
			if (HTTPContext::IsPostBack())
			{
			    //checks email
				$check = $this->controller_model->Execute(array('login'=>HTTPContext::$post['email']), 'sp_customers_get_by_login');
				if (empty($check))
				{
					$_SESSION['message'] = Language::Get("EMAIL NOT FOUND");
				}
				else
				{
        		    //new password generation
        		    $password = String::GenerateReadablePassword(8);

        		    //update password in DB
					$this->controller_model->Execute(array('id' => $check['id'], 'password' => md5($password)), 'sp_customers_update_password');

        		    //send email
        		    Gmail::Send(array
        		        (
            		        'fromName' => Language::Get('project_name'),
        		            'text' => Language::Get('Password Recovery Email').$password,
                            'recipients' => array(HTTPContext::$post['email']),
        		            'subject' => Language::Get('project_name').' :: '.Language::Get('Password Recovery'),
        		        )
        		    );

        			$_SESSION['message'] = ucfirst(Language::Get('Your new password was sent to')).' <b>'.HTTPContext::$post['email'].'</b>';
				}
			}

			$this->Redirect('customers/login/');
			exit();
		}
		
		
		/* PRIVATE PAGES */
		
		/**
		 * Logout
		 *
		 */
		function Logout()
		{
			$_SESSION = array();
			$this->Redirect('');
			exit();
		}
		
		/**
		 * Profile page
		 *
		 */
		function Profile()
		{
			$this->layout = 'site';
			$this->page_title = Language::Get('Profile');
			$this->module = 'profile';
			
			//reference data
			$this->data['reference'] = $this->GetReferenceData();		
			
			if (HTTPContext::IsPostBack())
			{
//				//profile update
//				$webService = new WebService();
//				unset(HTTPContext::$post['search']);
//				$updateResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
//					, "createOrUpdateWorkers"
//					, array('createOrUpdateWorkers' => array('mes:CreateOrUpdateWorkerRequest' => array('mes:worker' => HTTPContext::$post, 'attributes' => array('mergeProfile' => true))))
//					, array('XML_object_by_attributes' => true)
//					, array('SOAPAction' => 'createOrUpdateWorkers')
//					, array('mes' => 'http://mturk.nebulent.com/service/messages'));
////				Debugger::VarDump($updateResult);
//					
//				if (empty($updateResult['workers']))
//				{
//					$this->data['message']['text'] = Language::Get('Server error has occured. Please, try again.');
//					$this->data['message']['cssClass'] = 'error';
//				}
//				else
//				{	
//					$this->data['message']['text'] = Language::Get('Profile updated.');
//					$this->data['message']['cssClass'] = 'success';
//					
//					//registering into session
//					foreach ($updateResult['workers'] as $property => $value)
//					{
//						$property = str_replace('!', '', $property);
//						$_SESSION['customer'][$property] = $value;
//					}
//				}			
			}
			
			//worker basic info
			$this->data[$this->name] = HTTPContext::$session['customer'];
			
			//worker advanced info
			$webService = new WebService();
			$workerData = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "getWorkersData"
				, array('getWorkersData' => array('mes:workersUuids' => $this->data[$this->name]['uuid']))
				, array('XML_object_by_attributes' => false)
				, array('SOAPAction' => 'getWorkersData')
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($workerData);
			
			//interests process
			$interests = (!empty($workerData['workers']['interests']) && !isset($workerData['workers']['interests']['0'])) ? array('0' => $workerData['workers']['interests']) : $workerData['workers']['interests'];
			
			if (!empty($interests))
			{
				foreach ($interests as $interest)
				{
					$this->data['selected_interests'][] = $interest['!interestUuid'];
				}
			}
			else 
			{
				$this->data['selected_interests'] = array();
			}
			
			//locations process
			$locations = (!empty($workerData['workers']['geoLocations']) && !isset($workerData['workers']['geoLocations']['0'])) ? array('0' => $workerData['workers']['geoLocations']) : $workerData['workers']['geoLocations'];
			if (!empty($locations))
			{
				foreach ($locations as $key => $location)
				{
					$this->data['selected_locations'][$key]['geoLocationUuid'] = $location['!geoLocationUuid'];
					$this->data['selected_locations'][$key]['primaryResidenceIndicator'] = $location['!primaryResidenceIndicator'];
				}
			}
			else 
			{
				$this->data['selected_locations'] = array();
			}
			
			//languages process
			$languages = (!empty($workerData['workers']['languages']) && !isset($workerData['workers']['languages']['0'])) ? array('0' => $workerData['workers']['languages']) : $workerData['workers']['languages'];
			if (!empty($languages))
			{
				foreach ($languages as $key => $language)
				{
					$this->data['selected_languages'][$key]['languageUuid'] = $language['!languageUuid'];
					$this->data['selected_languages'][$key]['nativeIndicator'] = $language['!nativeIndicator'];
					$this->data['selected_languages'][$key]['canWriteIndicator'] = $language['!canWriteIndicator'];
					$this->data['selected_languages'][$key]['canReadIndicator'] = $language['!canReadIndicator'];
				}
			}
			else 
			{
				$this->data['selected_languages'] = array();
			}
		}
		
		/**
		 * Worker stats
		 *
		 */
		function Stats()
		{
			$this->layout = 'site';
			$this->page_title = Language::Get('Statistics');	
			$this->module = 'statistics';
			
			//worker statistics
			$webService = new WebService();
			$workerStats = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "getWorkersStatisticsSummary"
				, array('getWorkersStatisticsSummary' => array('mes:workersUuids' => HTTPContext::$session['customer']['uuid']))
				, array('XML_object_by_attributes' => false)
				, array('SOAPAction' => 'getWorkersStatisticsSummary')		
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($workerStats);

			//stats parsing
			if (!empty($workerStats['summaries']))
			{
				foreach ($workerStats['summaries'] as $statKey => $statValue)
				{
					$statKey = str_replace('!', '', $statKey);
					$this->data[$this->name][$statKey] = $statValue;
				}
			}
			else 
			{
				$this->data[$this->name] = array();
			}
			
			//DEMO: detailed stats
			for ($i = 0; $i < 10; $i++)
			{
				$this->data['stats'][$i] = array
				(
					'date' => '01-02-2011',
					'worker' => 'Anton Perkin',
					'campaign' => 'Test campaign',
					'qualification' => 'Lux',
				);			
			}
		}
		
		
		/* AJAX */
		
		/**
		 * Profile update
		 *
		 */
		public function UpdateProfile()
		{
			//profile update
			$webService = new WebService();
			unset(HTTPContext::$post['search']);
			$updateResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "createOrUpdateWorkers"
				, array('createOrUpdateWorkers' => array('mes:CreateOrUpdateWorkerRequest' => array('mes:worker' => HTTPContext::$post, 'attributes' => array('mergeProfile' => true))))
				, array('XML_object_by_attributes' => true)
				, array('SOAPAction' => 'createOrUpdateWorkers')
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($updateResult);
					
			if (empty($updateResult['workers']))
			{
				echo ": <span class = 'error'>Server error has occured. Please, try again.</span>";
			}
			else
			{	
				echo ": <span class = 'success'>updated successfully</span>";
				
				//registering into session
				foreach ($updateResult['workers'] as $property => $value)
				{
					$property = str_replace('!', '', $property);
					$_SESSION['customer'][$property] = $value;
				}
			}			
			
			exit();
		}		
		
		/**
		 * Interests update
		 *
		 */
		public function UpdateInterests()
		{
			$worker = array('attributes' => array('uuid' => HttpContext::$session['customer']['uuid']));
			$i = 0;
			foreach (HTTPContext::$post['interests'] as $interest)
			{
				if (empty($interest)) continue;
				$worker['interests_'.$i.'']['interestUuid'] = $interest;
				$i++;
			}

			$webService = new WebService();
			$updateResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "createOrUpdateWorkers"
				, array('createOrUpdateWorkers' => array('mes:CreateOrUpdateWorkerRequest' => array('mes:worker' => $worker, 'attributes' => array('mergeInterests' => true))))
				, array('XML_object_by_attributes' => true)
				, array('SOAPAction' => 'createOrUpdateWorkers')
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($updateResult);
			
			if (empty($updateResult['workers']))
			{
				echo ": <span class = 'error'>Server error has occured. Please, try again.</span>";
			}
			else
			{	
				echo ": <span class = 'success'>updated successfully</span>";
			}			
			
			exit();
		}
		
		/**
		 * Locations update
		 *
		 */
		public function UpdateLocations()
		{
			$worker = array('attributes' => array('uuid' => HttpContext::$session['customer']['uuid']));
			$i = 0;
			foreach (HTTPContext::$post['locations'] as $key => $location)
			{
				if (empty($location['geoLocationUuid'])) continue;
				$location['primaryResidenceIndicator'] = ($key == HTTPContext::$post['primaryResidenceIndicator']) ? 1: 0;
				$worker['geoLocations_'.$i.''] = $location;
				$i++;
			}

			$webService = new WebService();
			$updateResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "createOrUpdateWorkers"
				, array('createOrUpdateWorkers' => array('mes:CreateOrUpdateWorkerRequest' => array('mes:worker' => $worker, 'attributes' => array('mergeGeoLocations' => true))))
				, array('XML_object_by_attributes' => true)
				, array('SOAPAction' => 'createOrUpdateWorkers')
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($updateResult);
			
			if (empty($updateResult['workers']))
			{
				echo ": <span class = 'error'>Server error has occured. Please, try again.</span>";
			}
			else
			{	
				echo ": <span class = 'success'>updated successfully</span>";
			}			
			
			exit();
		}
		
		/**
		 * Languages update
		 *
		 */
		public function UpdateLanguages()
		{
			$worker = array('attributes' => array('uuid' => HttpContext::$session['customer']['uuid']));
			$i = 0;
			foreach (HTTPContext::$post['languages'] as $language)
			{
				if (empty($language['languageUuid'])) continue;
				$worker['languages_'.$i.''] = $language;
				$i++;
			}

			$webService = new WebService();
			$updateResult = $webService->XMLCall("http://mturk.nebulent.com/mturk-blazeds/ws/EdieWorkersWebService?wsdl"
				, "createOrUpdateWorkers"
				, array('createOrUpdateWorkers' => array('mes:CreateOrUpdateWorkerRequest' => array('mes:worker' => $worker, 'attributes' => array('mergeLanguages' => true))))
				, array('XML_object_by_attributes' => true)
				, array('SOAPAction' => 'createOrUpdateWorkers')
				, array('mes' => 'http://mturk.nebulent.com/service/worker/messages'));
//			Debugger::VarDump($updateResult);
			
			if (empty($updateResult['workers']))
			{
				echo ": <span class = 'error'>Server error has occured. Please, try again.</span>";
			}
			else
			{	
				echo ": <span class = 'success'>updated successfully</span>";
			}			
			
			exit();
		}
		
		
		/* ADMIN PAGES */
		
		/**
		 * Main controller page
		*/
		function Index()
		{
			$this->DefaultParameters();
			
			$parameters = array('num_rows');
			$this->data[$this->name] = $this->controller_model->ListItemsPaged($this->request->get, '', $parameters);
			$this->data['num_rows'] = $parameters['num_rows'];
		}

		/**
		 * Adds an item
		*/
		function Add()
		{
			//reference data
							
			if (HTTPContext::IsPostBack())
			{
				//password encryption
				$this->request->post['password'] = md5($this->request->post['password']);
				
				if ($this->controller_model->Update($this->request->post))
				{
					$this->Redirect($this->name);
				}
				else
				{
					$this->data[$this->name] = $this->request->post;				
				}
			}
			else
			{

			}	
		}

		/**
		 * Displays an item
		 * @param integer $id item id
		*/
		function View($id)
		{
			//customer
			$this->data[$this->name] = $this->controller_model->Get($id);
		}

		/**
		 * Edits an item
		 * @param integer $id item id
		*/
		function Edit($id)
		{
			//reference data

			//customer
			$this->data[$this->name] = $this->controller_model->Get($id);

			if (HTTPContext::IsPostBack())
			{
				if ($this->controller_model->Update($this->request->post))
				{
					$this->Redirect($this->name);
				}
				else
				{
					$this->data[$this->name] = $this->request->post;				
				}
			}
			else
			{

			}	
		}

		/**
		 * Deletes an item
		 * @param integer $id item id
		 * @param boolean $confirm delete confirmation
		*/
		function Delete($id, $confirm = 0)
		{ 
			if ($confirm)
			{
				$this->controller_model->Delete($id);
				$this->Redirect($this->name);
			}
			else
			{
				$this->layout = 'empty';
				$this->data[$this->name]['id'] = $id;
			}
		}
	}
?>